<?php

namespace App\Services\Setting\Setting;


use App\Models\Log\Log;
use App\Models\Setting\Setting;
use App\Services\Authcode\SettingCategory\SettingCategoryLogic;
use App\Services\BaseService;
use App\Services\Log\Log\LogLogic;

class SettingLogic extends BaseService
{
//
//    /*内部获取某个配置的详情*/
//    public function dbInfo($data)
//    {
//        return $this->db()->where(['id'=>$data['id'],'status'=>1])->find();
//    }
//
//    /*添加一个设置*/
//    public function addSet($data): array
//    {
//        unset($data['app_id']);
//        $res = $this->model($this->settingModel)->save($data);
//        return auto_return($res);
//    }
//
    /*后台编辑一个正常的配置*/
    public function editSet($data): array
    {
        if (is_array($data['other_info'])){
            $data['other_info'] = json_encode($data['other_info']);
        }

        if (isset($data['app_id']))
            unset($data['app_id']);

        $res =  Setting::where([
            'id'        => $data['id'],
            'status'    => 1
        ])->update($data);
        return auto_return($res);
    }

    public function editSetting($data)
    {
        $info = Setting::where('id', $data['id'])->first();
        $info->name = $data['name'];
        $info->value = $data['value'];

        $userInfo = $this->isLogin($data['token']);
        if(!$userInfo['res']['id'])
            return auto_failure(null, '请登录');
        $logData = [
            'id' => $userInfo['res']['id'],
            'name' => $userInfo['res']['name'],
            'type' => 1,
            'record' => '修改了'.$info['name'].'配置项'
        ];
        (new LogLogic())->addLog($logData);

        try {
            $res = $info->save();
            return $res ?
                auto_success($res, '修改成功') :
                auto_failure($res, '修改失败');
        } catch (\Exception $e) {
            return auto_failure($e->getMessage());
        }
    }

    /**
     * 后台获取某个不被删除的配置
     * @param $data
     * @return array
     */
    public function getOneSet($data): array
    {
        isset($data['id']) && $_where[] = ['setting.id', '=', $data['id']];
        !empty($data['action']) && $_where[] = ['setting.action', '=', $data['action']];
        $_where[] = ['setting.status', '<>', -1];
        $res = Setting::leftJoin('setting_category', 'setting.category_id', '=', 'setting_category.id')
            ->select('setting.*', 'setting_category.other_app_read')
            ->where($_where)
            ->first();

        $res =  auto_return($res);
        if($res['status'] != SUCCESS_STATUS){
            return $res;
        }

        $res['res']['cate_ids'] = (new SettingCategoryLogic())->getParentIds($res['res']['category_id']);
        return $res;
    }

    /**
     * 获取配置列表
     * @param $data
     * @return mixed
     */
    public function getSettingList($data)
    {
        $_where[] = ['status', '=', 1];
        if(isset($data['keywords']))
            $_where[] = ['name', 'like', '%'.$data['keywords'].'%'];
        $res = Setting::where($_where)->orderBy('id', 'desc')->paginate(10);
        return $res;
    }

    /*后台获取某个应用的不被删除的配置列表*/
    public function getAppSet($data): array
    {
        return $this->_getList($data);
    }

    /*检验识别码的唯一性*/
    public function checkAction($data): array
    {
        $info = Setting::where('action', $data['action'])->first();
        if($info){
            return auto_failure(null, '该识别码action已存在');
        }else{
            return auto_success(null, '识别码有效');
        }
    }
//
//    /*后台获取某些应用下的没被删除的配置列表 分类中的action*/
//    public function getCateSetList($data): array
//    {
//        $res = $this->_getList(['app_id'=>$data['app_id'],'category_action'=>$data['action']], 'setting', 'setting_category', $this->model($this->settingModel), false);
//
//        $returnRes = [];
//        foreach ($res['res'] as $k => $v) {
//            $returnRes[$v['action']] = $v['value'];
//        }
//
//        return auto_return($returnRes);
//    }
//
//    /*根据action获取多个配置详情 配置表中的action*/
//    public function getSomeSet($data): array
//    {
//        return $this->_getList($data, 'setting', 'setting_category', $this->model($this->settingModel), false);
//    }

    public function _getList(array $data, bool $isPageList = true): array
    {

        $_where[] = ['setting.status', '<>', -1];
        isset($data['user_id']) && $_where[] = ['setting.user_id', '=', $data['user_id']];

        if(isset($data['category_action'])){   //分类表中的action
            is_string($data['category_action']) && $data['category_action'] = explode(",", $data['category_action']);
            $_where[] = ['setting_category.action', 'in', $data['category_action']];
        }
        if(isset($data['action'])){   //非分类表中的action
            is_string($data['action']) && $data['action'] = explode(",", $data['action']);
            $_where[] = ['setting.action', 'in', $data['action']];
        }

//        $manageAppId = ApiBase::getAppId();
//        $_whereOr = $manageAppId == $data['app_id'] ? true : $joinCateTableName . '.`app_id`=' . $data['app_id'] . ' OR FIND_IN_SET(' . $data['app_id'] . ',`other_app_read`) OR ' . $joinCateTableName . '.is_public = 1';


        $query = Setting::leftJoin('setting_category', 'setting.category_id', '=', 'setting_category.id')
            ->select('setting.*', 'setting_category.other_app_read')
            ->where($_where)
            ->orderBy('setting.create_time', 'desc');
        if($isPageList){   //返回分页列表数据
            $res = $query->paginate($data['listRows'], null, null, $data['page']);
            $returnData = auto_return_page($res);
        }else{
            $res = $query->get()->toArray();
            $returnData = auto_return($res);
        }
        return $returnData;
    }

    /**
     * 添加具体配置
     * return array
     */
     public function addSet($data): array
     {
         $userInfo = $this->isLogin($data['token']);
         if(!$userInfo['res']['id'])
             return auto_failure(null, '请登录');
         unset($data['token']);
         $data['other_info'] = json_encode($data['other_info']);

         try {
             //判断识别码是否已存在
             $checkRes = Setting::where(['action' => $data['action']])->first();
             if($checkRes)
                 return auto_failure('该识别码已存在');
             $res = Setting::insert($data);
             $logData = [
                 'id' => $userInfo['res']['id'],
                 'name' => $userInfo['res']['name'],
                 'type' => 1,
                 'record' => $data['name'].'配置项'
             ];
             (new LogLogic())->addLog($logData);
             return auto_success($res);
         } catch (\Exception $e) {
             return auto_failure($e->getMessage(), '添加失败');
         }
     }
}
